/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package de.realriu.snipzel.control;

import com.uwyn.jhighlight.renderer.XhtmlRendererFactory;
import de.realriu.riulib.gui.imagelist.ReferenzImageList;
import de.realriu.riulib.helpers.ScaleImage;
import de.realriu.snipzel.Settings;
import de.realriu.snipzel.control.datastorage.FileStorage;
import de.realriu.snipzel.control.datastorage.Storageable;
import de.realriu.snipzel.gui.MainFrame;
import de.realriu.snipzel.model.CodeSnippet;
import de.realriu.snipzel.model.Comparators;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.imageio.ImageIO;

/**
 *
 * @author riu
 */
public class Controller implements Storageable{

    private Storageable store = new FileStorage(this);
    private MainFrame mainFrame;
    private CodeSnippet currentSnippet;
    private Map<String, RenderedImage> langImgs = new HashMap<String, RenderedImage>();
   

    public Controller(MainFrame mf) {
        mainFrame = mf;
    }

    public void unloadSnippet(){
        currentSnippet = null;
        mainFrame.getEp_snippet_code().setText("<html>   <head>    </head>   <body>     <p style=\"margin-top: 0\">            </p>   </body> </html> ");
        mainFrame.getBtn_remove().setEnabled(false);
    }

    public RenderedImage getImageForLang(String lang){
        return langImgs.get(lang);
    }

    public void updateMyData() throws IOException{

        ReferenzImageList<CodeSnippet> snippet_list = mainFrame.getSnippet_list();
        snippet_list.clear();
        CodeSnippet[] snippets = loadAllSnippets(true);
        for(CodeSnippet cs : snippets){
            snippet_list.addImage((Image)langImgs.get(cs.getLanguage()), cs.getTitle(), cs);
        }

        snippet_list.sort(new Comparators.AlphabeticTitleComparator(), true, 85, true, ReferenzImageList.SortAlgorithm.Quicksort);
//        long v = Math.max(getMyVersion(), getCentralVersion()) + 1;
//        PrintStream ps = new PrintStream(new File(Settings.getSetting("work-dir")+System.getProperty("file.separator")+"version"));
//        ps.println(v);
//        ps.close();

        Settings.setSetting("version", ""+getCentralVersion());
    }    

    public boolean saveSnippet(CodeSnippet cs) throws IOException {
        return store.saveSnippet(cs);
    }

    public boolean updateSnippet(CodeSnippet cs) throws IOException {
        return store.updateSnippet(cs);
    }

    public CodeSnippet loadSnippet(long id, boolean lazy) throws IOException {
        CodeSnippet cs = store.loadSnippet(id, lazy);
        if(!lazy){
            currentSnippet = cs;
            String url = getURL(currentSnippet);
            mainFrame.getEp_snippet_code().setPage(url);
            mainFrame.getBtn_remove().setEnabled(true);
        }
        return cs;
    }

    public CodeSnippet[] loadAllSnippets(boolean lazy) throws IOException {
        return store.loadAllSnippets(lazy);
    }

    public boolean deleteSnippet(CodeSnippet cs) throws IOException {
        if(cs == currentSnippet){
            unloadSnippet();
        }
        return store.deleteSnippet(cs);
    }

    public boolean initWorkDirectory() throws IOException {
        store.initWorkDirectory();

        try{
            RenderedImage i = ImageIO.read(getClass().getResource("/de/realriu/snipzel/resource/nopic.png"));
            i = ScaleImage.scale((BufferedImage)i, getMainFrame().getSnippet_list().getWidth(), getMainFrame().getSnippet_list().getWidth());
            langImgs.put(CodeSnippet.UNKNOWN_LANGUAGE_STRING, i);

            for(String s : (Set<String>)XhtmlRendererFactory.getSupportedTypes()){
                String r = "/de/realriu/snipzel/resource/"+s+".png";
                //System.out.println(r);
                i = ImageIO.read(getClass().getResource(r));
                i = ScaleImage.scale((BufferedImage)i, getMainFrame().getSnippet_list().getWidth(), getMainFrame().getSnippet_list().getWidth());
                langImgs.put(s, i);
            }

        }catch(Exception e){e.printStackTrace(); System.exit(1);}

        Thread updater = new Thread(){

            @Override
            public void run() {
                synchronized(this){
                    while(mainFrame.getSnippet_list().getWidth()<=1){
                        try{wait(100);}catch(Exception e){};
                    }
                }
                while(true){
                    long checkIntervall = 0;
                    try {
                        checkIntervall = Long.parseLong(Settings.getSetting("check-intervall"));
                    }catch(Exception e){
                        Settings.setSetting("check-intervall", (checkIntervall = 15000)+"");
                    }

                    try{
                        if(getMyVersion() < getCentralVersion()){
                            System.out.println("New Version found, updating...");
                            updateMyData();
                            System.out.println("Updated to version "+getMyVersion());
                        }
                    }catch(Exception e){e.printStackTrace();}
                    try{sleep(checkIntervall);}catch(Exception e){}
                }
            }

        };
        updater.setDaemon(true);
        updater.start();

        synchronized(this){
            while(mainFrame.getSnippet_list().getWidth()<=1){
                try{wait(100);}catch(Exception e){};
            }

            updateMyData();
        }
        return true;
    }

    public String getURL(CodeSnippet cs) throws IOException {
        return store.getURL(cs);
    }

    public MainFrame getMainFrame() {
        return mainFrame;
    }

    public long getNewSnippetID() throws IOException {
        return store.getNewSnippetID();
    }

    public CodeSnippet getCurrentSnippet() {
        return currentSnippet;
    }

    public long getCentralVersion() throws IOException {
        return store.getCentralVersion();
    }

    public long getMyVersion() throws IOException {
        return store.getMyVersion();
    }

        
    

}
